package ar.com.spsolutions.splibrary.repositories;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

import ar.com.spsolutions.splibrary.user.User;

public class UserRepository extends HibernateGenericDAO<User> implements
		GenericRepository<User> {

	private static final long serialVersionUID = -1485581113302662573L;
	private static final String UNCHECKED = "unchecked";
	private static final String NAME_PROPERTY = "name";

	public UserRepository() {
		super(User.class);
	}

	public User findByName(final String name) {
		return this.findByEq(UserRepository.NAME_PROPERTY, name);
	}

	public int sizeOfSearch(final String searchValue) {
		final DetachedCriteria criteria = this.createDetachableCriteria();
		criteria.add(Restrictions.ilike(UserRepository.NAME_PROPERTY,
				searchValue, MatchMode.ANYWHERE));
		return this.getHibernateTemplate().findByCriteria(criteria).size();
	}

	@SuppressWarnings(UserRepository.UNCHECKED)
	public List<? extends User> getResults(final String searchValue,
			final int first, final int count) {
		final DetachedCriteria criteria = this.createDetachableCriteria();
		criteria.add(Restrictions.ilike(UserRepository.NAME_PROPERTY,
				searchValue, MatchMode.ANYWHERE));
		return this.getHibernateTemplate().findByCriteria(criteria, first,
				count);
	}

	public void flush() {
		this.getHibernateTemplate().flush();
	}
}
